local TargetView = require("app.battleV3.ui.views.subviews.TargetView")
local ReviveStar = require("app.battleV3.ui.objs.ReviveStar")

local TopView = MClass("TopView")

local ColorWarnning = cc.c3b(242, 0, 0)
local ColorNormal = cc.c3b(242, 253, 135)

local ColorRed = cc.c4b(253, 103, 63,255)
local ColorBlue = cc.c4b(99, 195, 226,255)
local TAP_ZORDER = 999

function TopView:ctor(battleType)
    --self.root 默认为根节点
    --Button
    self.autoButton = self.root:findChild("btn_auto")
    self.tips = self.root:findChild("btn_auto/tips")
    self.tipsTlt  = self.tips:findChild("Panel/tlt")
    self.tipsBg = self.tips:findChild("Panel/bg")
    self.guideAutoTips = self.root:findChild("btn_auto/tips_1")
    self.guideAutoTipsTlt = self.guideAutoTips:findChild("Panel/tlt")
    self.guideAutoTipsBg = self.guideAutoTips:findChild("Panel/bg")
    self:_setTipsString(L("guide401"),self.guideAutoTipsTlt,self.guideAutoTipsBg)
    self.escButton = self.root:findChild("btn_esc")
    self.setButton = self.root:findChild("btn_set")

    --time label
    self.timeLabel = self.root:findChild("clock/time")
    --tips label
    self.tipsLabel = self.root:findChild("Tips_skill")

    local jjcNode = self.root:findChild("jjc_top")
    if battleType == Enums.EBattleType.BtType_ArenaPvp
      or battleType == Enums.EBattleType.BtType_Throne
      or battleType == Enums.EBattleType.BtType_WorldGuildWar then
        jjcNode:setVisible(true)
        self.pvpTopNode = self.root:findChild("jjc_top/Panel")
        self.leftKillTimesBg = self.pvpTopNode:findChild("bg/bg_a")
        self.rightKillTimesBg = self.pvpTopNode:findChild("bg/bg_b")
        self.leftKillTimesLabel = self.pvpTopNode:findChild("num_1")
        self.rightKillTimesLabel = self.pvpTopNode:findChild("num_2")

        self.leftReviveStars = {}
        self.rightReviveStars = {}
        for i = 1, Constant.BattleReviveHeartCount do
            --左方
            self.leftReviveStars[i] = ReviveStar.new(self.pvpTopNode:findChild("b_"..i))
            self.leftReviveStars[i]:setVisible(false)
            --右方
            self.rightReviveStars[i] = ReviveStar.new(self.pvpTopNode:findChild("r_"..i))
            self.rightReviveStars[i]:setVisible(false)
        end
    else
        jjcNode:setVisible(false)
    end

    --target view
    self.targetView = TargetView.new(self.root:findChild("top_head"))

    --设置事件
    self:init()
end

function TopView:init()
    BattleUIEvent:addObjToFrameUpdate(self,TopView.updateFrame)
    self.escButton:setVisible(false)
    self.tipsLabel:setVisible(false)
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_PVP_INIT_TOP,handler(self,TopView.initBattlePvpTop))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_TIME,handler(self,TopView.setTime))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.ESCAPE_SHOWUI,handler(self,TopView.showEscape))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_FMTION,handler(self,TopView.showBattleTopLabel))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_PVP_FEFRESH_TOP,handler(self,TopView.refreshBattlePvpTop))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_SET_ABLE,handler(self,TopView.enableEsc))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_CANCEL_AUTO,handler(self,TopView.cancelAutoBattle))
    self:setSetup()
end

function TopView:cancelAutoBattle()
    --取消自动战斗
    EM:notify("onSettinAutoBattle", false)
    self.startTime = app.session:getServerTime() or app:getUTCTime()
end

function TopView:updateFrame()
    if not self.startTime then
        return
    end
    self.duleTime = app.session:getServerTime() or app:getUTCTime()
    if self.duleTime-self.startTime > Constant.BattleAutoCancelInterval then
        EM:notify("onSettinAutoBattle", self.lastAutoBattle)
        self.startTime = nil
    end
end

function TopView:reset()
    local setting = UD.setting
    setting:setAutoBattle(self.lastAutoBattle)
end

function TopView:showEscape()
    self.bShowEsc = true
    self.escButton:setVisible(true)
    self.escButton:setEnabled(false)
    self.escButton:setOpacity(155)
end

function TopView:hideEscape()
    self.bShowEsc = false
    self.escButton:setVisible(false)
end

function TopView:enableEsc(bAble)
    if bAble and self.bShowEsc then
        self.escButton:setVisible(true)
        self.escButton:setEnabled(true)
        self.escButton:setOpacity(255)
    end
end

function TopView:showBattleTopLabel(str)
    -- body
    self.tipsLabel:setVisible(true)
    self.tipsLabel:setString(str)
end

function TopView:initBattlePvpTop(event)
    local isSelfLeft = event.isSelfLeft
    local initReviveTimes = event.initReviveTimes
    local maxReviveTimes = event.maxReviveTimes
    if initReviveTimes == 0 then
        initReviveTimes = maxReviveTimes
    end
    if isSelfLeft then
        self.leftKillTimesLabel:getVirtualRenderer():setColor(ColorBlue)
        self.rightKillTimesLabel:getVirtualRenderer():setColor(ColorRed)
        self.leftKillTimesBg:setVisible(true)
        self.rightKillTimesBg:setVisible(false)
    else
        self.leftKillTimesLabel:getVirtualRenderer():setColor(ColorRed)
        self.rightKillTimesLabel:getVirtualRenderer():setColor(ColorBlue)
        self.leftKillTimesBg:setVisible(false)
        self.rightKillTimesBg:setVisible(true)
    end

    for i = 1, maxReviveTimes do
        --左方
        self.leftReviveStars[i]:setVisible(true)
        self.leftReviveStars[i]:setIsSelf(isSelfLeft)
        --右方
        self.rightReviveStars[i]:setVisible(true)
        self.rightReviveStars[i]:setIsSelf(not isSelfLeft)
        if i > initReviveTimes then
            self.leftReviveStars[i]:setIsShow(false)
            self.rightReviveStars[i]:setIsShow(false)
        end
    end
    self.maxReviveTimes = maxReviveTimes
end

function TopView:refreshBattlePvpTop(event)
    self:hideEscape()

    local leftReviveTimes = event.leftReviveTimes
    local rightReviveTimes = event.rightReviveTimes
    local leftKillTimes = event.leftKillTimes
    local rightKillTimes = event.rightKillTimes

    --print("========refreshBattlePvpTop leftReviveTimes:",leftReviveTimes)
    --print("========refreshBattlePvpTop rightReviveTimes:",rightReviveTimes)
    --print("========refreshBattlePvpTop leftKillTimes:",leftKillTimes)
    --print("========refreshBattlePvpTop rightKillTimes:",rightKillTimes)

    self.tipsLabel:setVisible(false)
    self.pvpTopNode:setVisible(true)

    self.leftKillTimesLabel:setString(leftKillTimes)
    self.rightKillTimesLabel:setString(rightKillTimes)

    for i = 1, self.maxReviveTimes do
        self.leftReviveStars[i]:setIsShow( i <= leftReviveTimes )
        self.rightReviveStars[i]:setIsShow( i <= rightReviveTimes )
    end
end

function TopView:setSetup()
    local setting = UD.setting
    self.autoButton:setBright(not setting:getIsAutoBattle())
    self.autoButton:setLocalZOrder(TAP_ZORDER)
    local autoTaskId = tonumber(GD:getSystemPar("AutoBattleGuideTask",901010490))
    local isGuideAutoTips = UD:getValueFromGenericByKey("isClickAutoBattleBtn")
    --print(isGuideAutoTips,autoTaskId, UD:isMainTaskFinished(autoTaskId))
    if not isGuideAutoTips and UD:isMainTaskFinished(autoTaskId) then
        self.guideAutoTips:setVisible(true)
    else
        self.guideAutoTips:setVisible(false)
    end

    --自动战斗
    self.lastAutoBattle = setting:getIsAutoBattle()
    local function touchEvent_autoBattle(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            if setting:getIsAutoBattle() then
                sender:setBright(true)
                setting:setAutoBattle(false)
                EM:notify("onSettinAutoBattle", false)
                self.lastAutoBattle = false
            else
                sender:setBright(false)
                setting:setAutoBattle(true)
                EM:notify("onSettinAutoBattle", true)
                self.lastAutoBattle = true
            end

            if sender:isBright() then
                self.tips:setVisible(true)
                --计算字符串长度 动态设置底板的宽度
                self:_setTipsString(L("closeautobattle"),self.tipsTlt,self.tipsBg)

                self:performWithDelay(function()
                    self.tips:setVisible(false)
                end,0.5)
            else
                self.tips:setVisible(true)
                self:_setTipsString(L("openautobattle"),self.tipsTlt,self.tipsBg)

                self:performWithDelay(function()
                    self.tips:setVisible(false)
                end,0.5)
            end
        end
        UD:updateSetting(setting)

        if not isGuideAutoTips then
            UD:saveGeneric("isClickAutoBattleBtn",true)
            isGuideAutoTips = true
            self.guideAutoTips:setVisible(false)
        end
    end
    self.autoButton:addTouchEventListener(touchEvent_autoBattle)

    --逃跑
    local function touchEvent_Esc(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local function okFunc()
                BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.BATTLE_ESCAPE)
            end
            app:popMessage("escape", nil, {ok = okFunc}, Enums.ToastTag.battle)
        end
    end
    self.escButton:addTouchEventListener(touchEvent_Esc)

    --设置
    local function touchEvent_setting(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            UIHandler:handleMessage({id=Constant.FUNC_TYPE_SET, mode="open", data=2})
        end
    end
    self.setButton:addTouchEventListener(touchEvent_setting)
end

function TopView:_setTipsString(str,text,bg)
    local textHeight = text:getContentSize().height
    text:setString(str)
    text:getVirtualRenderer():setDimensions( 0, textHeight)
    local size = text:getVirtualRendererSize()
    text:setContentSize(size.width, textHeight)
    local bgSize = bg:getContentSize()
    bg:setContentSize(size.width + 32, bgSize.height)
end


function TopView:setTime(time)
    time = tonumber(time)
    local second = math.floor(time/1000) -- 总秒
    local min = math.floor(second/60) -- 分
    second = math.floor(second%60) -- 分
    if not cc.isDead(self.timeLabel) then
        self.timeLabel:setString(string.format("%02d:%02d",min,second))
        if time < 60000 then
            self.timeLabel:setColor(ColorWarnning)
        else
            self.timeLabel:setColor(ColorNormal)
        end
    end
end

function TopView:updateTargetData()

end

return TopView